<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 消息模型
 *
 * @author www.dingwei.cn
 */

class DlnMessageModel extends MY_Model{
	
	public $tbMessage = 'deliveryman_message';
	public $tbMessageDelete = 'deliveryman_message_delete';
	public $tbMessageViewed = 'deliveryman_message_viewed';
	
	/**
	 * 查看是否有新的消息
	 */
	public function hasNewMessage($userId){
	    
	    $this->db->join($this->mMessage->tbMessageViewed.' v', 'v.message_id = m.id', 'left')
        	     ->join($this->mMessage->tbMessageDelete.' d', 'd.message_id = m.id', 'left')
        	     ->where('(m.deliveryman_id = '.$userId.' or m.deliveryman_id = 0) 
                        and d.message_id is null and v.message_id is null');
	    
	    if($this->count($this->tbMessage.' m')){
	       return true;    
	    }
	     
	    return false;
	}

    /**
     * 获取新消息数量
     */
    public function newMessageCount($userId){

        $this->db->select('count(if(m.type = 1, m.id, null)) as sTotal,
                            count(if(m.type = 2, m.id, null)) as oTotal')
            ->join($this->mMessage->tbMessageViewed.' v', 'v.message_id = m.id', 'left')
            ->join($this->mMessage->tbMessageDelete.' d', 'd.message_id = m.id', 'left')
            ->where('(m.deliveryman_id = '.$userId.' or m.deliveryman_id = 0) 
                        and d.message_id is null and v.message_id is null');

       $tA = $this->getOne($this->tbMessage.' m');

        return $tA;
    }

    /**
     * 保存消息
     * @param array $data 数据
     * @param int   $id 消息id
     * @param int   $orderId 订单id
     * @return boolean|boolean|number
     * @author zyl
     */
    public function save($data, $id = 0, $orderId = 0){

        if ($id){
            $this->db->where('id',$id);
            $query = $this->update($this->tbMessage, $data);
            return $query === false ? false : true;
        } elseif ($orderId){

            $this->db->where('order_id',$orderId);
            $query = $this->update($this->tbMessage, $data);
            return $query === false ? false : true;
        }else{
            return $this->insert($this->tbMessage, $data);
        }
    }

    /**
     * 判断订单消息是否存在
     *
     * @param	string	$mobile	//手机号码
     * @return	boolean
     */
    public function messageIsExist($orderId){

        if( ! $orderId) return false;
        $this->db->select('d.message_id')
            ->join($this->tbMessageDelete.' d', 'd.message_id = m.id')
            ->where(array('m.order_id' => $orderId));

        $tA = $this->getOne($this->tbMessage.' m');

        if($tA){
            return $tA['message_id'];
        }

        return false;
    }
	
}